package com.lizemin;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class HQLQueryManyTable {

    Session session = null;
    Transaction tx = null;

    @Before
    public void init(){
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml") // configures settings from hibernate.cfg.xml
                .build();
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata()
                .buildSessionFactory();
        //创建SQL session连接
        session = sessionFactory.openSession();
        //开启事务
        tx = session.beginTransaction();
    }

    @After
    public void closeConnection() {
        if (null != session && session.isOpen()){
            //关闭session
            session.close();
        }
    }

    /**
     * 多表查询：显示客户名称和订单名称,通过内连接查询交集
     */
    @Test
    public void test1(){
        Query query = session.createQuery("select c.name,o.name from Customer c inner join c.orders o");
        List<Object[]> list = query.list();
        for (Object[] objects : list) {
            for (Object object : objects) {
                System.out.print(object + "\t");
            }
        }
    }

    /**
     * 多表查询：显示客户名称和订单名称,通过左连接查询交集+左表
     */
    @Test
    public void test2(){
        Query query = session.createQuery("select c.name,o.name from Customer c left join c.orders o");
        List<Object[]> list = query.list();
        for (Object[] objects : list) {
            for (Object object : objects) {
                System.out.print(object + "\t");
            }
            System.out.println();
        }
    }

    /**
     * 多表查询：显示客户名称和订单名称,通过右连接查询交集+右表
     */
    @Test
    public void test3(){
        Query query = session.createQuery("select c.name,o.name from Customer c right join c.orders o");
        List<Object[]> list = query.list();
        for (Object[] objects : list) {
            for (Object object : objects) {
                System.out.print(object + "\t");
            }
            System.out.println();
        }
    }


}
